package minjre.utils;

import java.io.*;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-05-28 16:03
 */
public class FileUtils {

    public static void copyFile(File src, File dest){
        try (
                FileInputStream in = new FileInputStream(src);
        ){
            copyFile(in,dest);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(InputStream in, File dest){
        try (
                FileOutputStream out = new FileOutputStream(dest);
        ){

            byte[] buf = new byte[1024 * 8];
            int len = 0;
            while((len = in.read(buf)) != -1){
                out.write(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果目录不存在，创建目录
     * @param file
     * @return
     */
    public static void mkdirParentIfUnExist(File file){
        File parent = new File(file.getParent());
        if(!parent.exists()){
            parent.mkdirs();
        }
    }

    /**
     * 递归删除文件
     * @param destFile
     */
    public static void delete(File destFile) {
        if(destFile.isDirectory() && destFile.listFiles().length != 0){
            File[] files = destFile.listFiles();
            for (File file : files) {
                delete(file);
            }
        }
        destFile.delete();
    }
}
